<template>
  <div class="resume-share-container">
    <!-- 页面头部 -->
    <div class="page-header">
      <div class="header-left">
        <h2>简历分享</h2>
        <p>发现优秀的简历模板，一键使用</p>
      </div>
    </div>

    <!-- 分享简历列表 -->
    <div class="shared-resumes">
      <el-row :gutter="20" v-if="sharedResumes.length > 0">
        <el-col :span="8" v-for="resume in paginatedSharedResumes" :key="resume.id">
          <el-card class="shared-resume-card" @click="handleView(resume.id)">
            <div class="resume-card-header">
              <h3 class="resume-title">{{ resume.resume_name }}</h3>
              <el-tag type="success" size="small">已分享</el-tag>
            </div>
            
            <div class="resume-card-content">
              <div class="resume-info">
                <p v-if="resume.basic_info?.name" class="resume-name">
                  <el-icon><User /></el-icon>
                  {{ resume.basic_info.name }}
                </p>
                <p v-if="resume.basic_info?.intention" class="resume-intention">
                  <el-icon><Briefcase /></el-icon>
                  {{ resume.basic_info.intention }}
                </p>
              </div>
              
              <div class="resume-meta">
                <span class="meta-item">
                  <el-icon><Calendar /></el-icon>
                  {{ formatDate(resume.created_at) }}
                </span>
                <span class="meta-item">
                  <el-icon><User /></el-icon>
                  用户{{ resume.user_id }}
                </span>
              </div>
            </div>
            
            <div class="resume-card-actions">
              <el-button @click.stop="handleView(resume.id)" type="primary" size="small">
                <el-icon><View /></el-icon>
                查看
              </el-button>
              <el-button @click.stop="handleUse(resume)" type="success" size="small">
                <el-icon><Download /></el-icon>
                使用模板
              </el-button>
              <el-button 
                @click.stop="handleFavorite(resume)" 
                :type="getFavoriteStatus(resume.id) ? 'warning' : 'default'"
                size="small"
                :loading="favoriteLoading[resume.id]"
              >
                <el-icon v-if="!favoriteLoading[resume.id]">
                  <StarFilled v-if="getFavoriteStatus(resume.id)" />
                  <Star v-else />
                </el-icon>
                {{ getFavoriteStatus(resume.id) ? '已收藏' : '收藏' }}
              </el-button>
            </div>
          </el-card>
        </el-col>
      </el-row>
      
      <!-- 空状态 -->
      <div v-else class="empty-state">
        <el-empty description="暂无分享的简历">
          <el-button @click="goToMyResumes" type="primary">
            <el-icon><Plus /></el-icon>
            去分享我的简历
          </el-button>
        </el-empty>
      </div>
    </div>

    <!-- 分页 -->
    <div class="pagination-container" v-if="sharedResumes.length > 0">
      <el-pagination
        v-model:current-page="currentPage"
        :page-size="pageSize"
        :total="totalShared"
        layout="prev, pager, next"
        :hide-on-single-page="true"
        @current-change="handlePageChange"
      />
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue';
import { useRouter } from 'vue-router';
import { ElMessage } from 'element-plus';
import { User, Briefcase, Calendar, View, Download, Plus, Star, StarFilled } from '@element-plus/icons-vue';
import axios from 'axios';

const router = useRouter();

// 数据
const sharedResumes = ref([]);
const loading = ref(false);

// 收藏相关
const favoriteStatus = ref({}); // { resumeId: favoriteId } 或 { resumeId: null }
const favoriteLoading = ref({});

// 分页相关
const currentPage = ref(1);
const pageSize = ref(9); // 每页显示9条（3列，每列3条）
const totalShared = computed(() => sharedResumes.value.length);

// 计算属性 - 分页数据
const paginatedSharedResumes = computed(() => {
  const start = (currentPage.value - 1) * pageSize.value;
  const end = start + pageSize.value;
  return sharedResumes.value.slice(start, end);
});

// 加载分享的简历列表
const loadSharedResumes = async () => {
  try {
    loading.value = true;
    const response = await axios.get('http://localhost:7001/api/resumes/shared');
    
    if (response.data.code === 0) {
      sharedResumes.value = response.data.data.list || [];
      // 加载完成后检查收藏状态
      await checkFavoriteStatus();
    } else {
      ElMessage.error(response.data.msg || '加载分享简历列表失败');
    }
  } catch (error) {
    console.error('加载分享简历列表失败:', error);
    ElMessage.error('加载分享简历列表失败，请重试');
  } finally {
    loading.value = false;
  }
};

// 格式化日期
const formatDate = (dateString) => {
  if (!dateString) return '未知';
  const date = new Date(dateString);
  return date.toLocaleDateString('zh-CN');
};

// 分页处理
const handlePageChange = (page) => {
  currentPage.value = page;
  // 滚动到顶部
  window.scrollTo({ top: 0, behavior: 'smooth' });
};

// 查看简历
const handleView = (resumeId) => {
  router.push(`/resume/${resumeId}`);
};

// 使用模板
const handleUse = (resume) => {
  // 检查模板是否可用（只有分享的简历对应的模板才能使用）
  if (!resume.template_id) {
    ElMessage.error('该简历没有关联的模板，无法使用');
    return;
  }
  
  // 直接跳转到创建页面，不传递任何参数，让编辑器进入纯创建模式
  router.push({
    path: '/editor',
    query: { 
      createNew: 'true',
      templateId: resume.template_id
    }
  });
};

// 去我的简历页面
const goToMyResumes = () => {
  router.push('/my-resumes');
};

// 检查简历收藏状态
const checkFavoriteStatus = async () => {
  if (sharedResumes.value.length === 0) return;
  
  const userId = parseInt(localStorage.getItem('userId') || 1);
  
  for (const resume of sharedResumes.value) {
    try {
      const response = await axios.get('http://localhost:7001/api/favorites/check', {
        params: {
          user_id: userId,
          resume_id: resume.id
        }
      });
      
      if (response.data.code === 0) {
        favoriteStatus.value[resume.id] = response.data.data.isFavorite ? response.data.data.favoriteId : null;
      }
    } catch (error) {
      console.error(`检查简历 ${resume.id} 收藏状态失败:`, error);
    }
  }
};

// 获取简历收藏状态
const getFavoriteStatus = (resumeId) => {
  return !!favoriteStatus.value[resumeId];
};

// 切换简历收藏
const handleFavorite = async (resume) => {
  const userId = parseInt(localStorage.getItem('userId') || 1);
  const favoriteId = favoriteStatus.value[resume.id];
  
  favoriteLoading.value[resume.id] = true;
  
  try {
    if (favoriteId) {
      // 取消收藏
      const response = await axios.delete(`http://localhost:7001/api/favorites/${favoriteId}`, {
        params: { user_id: userId }
      });
      
      if (response.data.code === 0) {
        favoriteStatus.value[resume.id] = null;
        ElMessage.success('已取消收藏');
      } else {
        ElMessage.error(response.data.msg || '取消收藏失败');
      }
    } else {
      // 收藏
      const favoriteData = {
        user_id: userId,
        resume_type: 1,
        resume_id: resume.id,
        resume_name: resume.resume_name
      };
      
      const response = await axios.post('http://localhost:7001/api/favorites', favoriteData);
      
      if (response.data.code === 0) {
        favoriteStatus.value[resume.id] = response.data.data.id;
        ElMessage.success('收藏成功');
      } else {
        ElMessage.error(response.data.msg || '收藏失败');
      }
    }
  } catch (error) {
    console.error('收藏操作失败:', error);
    ElMessage.error('操作失败，请重试');
  } finally {
    favoriteLoading.value[resume.id] = false;
  }
};

// 页面加载时获取数据
onMounted(() => {
  loadSharedResumes();
});
</script>

<style scoped>
.resume-share-container {
  min-height: 100vh;
  background: linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%);
  padding: 20px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 30px;
  padding: 24px;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  border-radius: 12px;
  box-shadow: 0 8px 32px rgba(102, 126, 234, 0.15);
}

.header-left h2 {
  margin: 0 0 8px 0;
  color: #fff;
  font-size: 24px;
  font-weight: 600;
}

.header-left p {
  margin: 0;
  color: rgba(255, 255, 255, 0.8);
  font-size: 14px;
}

.shared-resumes {
  max-width: 1200px;
  margin: 0 auto;
}

.shared-resume-card {
  margin-bottom: 20px;
  border-radius: 12px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.1);
  border: none;
  cursor: pointer;
  transition: all 0.3s ease;
}

.shared-resume-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 8px 30px rgba(0, 0, 0, 0.15);
}

.resume-card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15px;
}

.resume-title {
  margin: 0;
  font-size: 16px;
  font-weight: 600;
  color: #333;
  flex: 1;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.resume-card-content {
  margin-bottom: 15px;
}

.resume-info {
  margin-bottom: 10px;
}

.resume-name,
.resume-intention {
  margin: 5px 0;
  font-size: 14px;
  color: #666;
  display: flex;
  align-items: center;
  gap: 5px;
}

.resume-meta {
  display: flex;
  flex-direction: column;
  gap: 5px;
}

.meta-item {
  display: flex;
  align-items: center;
  gap: 5px;
  font-size: 12px;
  color: #999;
}

.resume-card-actions {
  display: flex;
  gap: 8px;
  justify-content: flex-end;
}

.empty-state {
  text-align: center;
  padding: 60px 20px;
}

.pagination-container {
  display: flex;
  justify-content: center;
  margin-top: 30px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .page-header {
    flex-direction: column;
    gap: 20px;
  }
  
  .resume-card-actions {
    flex-direction: column;
  }
  
  .resume-card-actions .el-button {
    width: 100%;
  }
}
</style>
